package com.wwwarehouse.resource_center.fragment.createobject.creategoods;

import android.os.Bundle;
import android.os.Parcelable;
import android.support.v4.app.Fragment;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;

import com.alibaba.fastjson.JSON;
import com.wwwarehouse.common.activity.BaseCardDeskActivity;
import com.wwwarehouse.common.adapter.carddesk.MyFragmentPagerAdapter;
import com.wwwarehouse.common.bean.response.CommonClass;
import com.wwwarehouse.common.custom_widget.CustomViewPagerInternal;
import com.wwwarehouse.common.custom_widget.ElasticScrollView;
import com.wwwarehouse.common.tools.LogUtils;
import com.wwwarehouse.common.tripartite_widget.viewindicator.CirclePageIndicator;
import com.wwwarehouse.resource_center.R;
import com.wwwarehouse.resource_center.adapter.rules.MyPagerAdapter;
import com.wwwarehouse.resource_center.bean.goods.GoodsAttributesBean;
import com.wwwarehouse.resource_center.constant.ResourceConstant;
import com.wwwarehouse.resource_center.eventbus_event.GoodsEvent;
import com.wwwarehouse.resource_center.eventbus_event.RulesEvent;
import com.wwwarehouse.resource_center.fragment.rules.TheParentFragment;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import de.greenrobot.event.EventBus;

/**
 * @author Joseph on 2017/9/18.
 *         <p/>
 *         选择属性
 */

public class GoodsAttributesSelectParentFragment extends TheParentFragment implements View.OnClickListener {

    CustomViewPagerInternal viewPager;
    CustomViewPagerInternal mSearchPager;
    CirclePageIndicator pageIndicator;
    CirclePageIndicator mSearchIndicator;
    ArrayList<Fragment> fragmentList;
    ArrayList<Fragment> mSearchFragmentList;
    ElasticScrollView elasticScrollView;
    MyFragmentPagerAdapter adapter;
    MyPagerAdapter mSearchAdapter;
    private boolean isShow = true;
    private String searchName;
    private int currentPos;
    List<GoodsAttributesBean.ListBean> mSelectList = new ArrayList<>();
    private Button  mConfirm ;
    private Button  mSelected ;
    int mNum = 24;
    public static final int SELECT_ATTRIBUTE_BYNAME = 1;  //全部属性
    public static final int SEARCH_ATTRIBUTE_BYNAME = 2;  //根据属性名模糊查找属性
    public static final int SELECT_ATTRIBUTE_BYCATEGORY = 3;  //根据类目找属性
//    private String categoryUkid;
//    private String businessId;
    ArrayList<GoodsAttributesBean.ListBean> listBeen; //  维护属性返回的全部属性
    @Override
    protected int getContentId() {
        return R.layout.fragment_goods_select_the_attributes;
    }

    @Override
    public void setTitle() {
        if (peekFragment() instanceof GoodsAttributesSelectParentFragment){
            mActivity.setTitle(R.string.attributes_select);
        }
    }

    @Override
    protected void init(View view) {
        EventBus.getDefault().register(this);
        elasticScrollView = findView(view, R.id.elastic_scroll);
        viewPager = findView(view, R.id.task_pager);
        pageIndicator = findView(view, R.id.pager_indicator);
        mConfirm = findView(view, R.id.confirm);
        mSelected = findView(view, R.id.selected);
        mSearchPager = findView(view, R.id.search_pager);
        mSearchIndicator = findView(view, R.id.search_indicator);
        elasticScrollView.setOnPullListener(new ElasticScrollView.OnPullListener() {
            @Override
            public void onDownPull() {
                if (isShow) {
                    ((BaseCardDeskActivity) mActivity).hideSortBt();
                    ((BaseCardDeskActivity) mActivity).hideFilterBt();
                    ((BaseCardDeskActivity) mActivity).showSearchTitle();
                } else {
                    ((BaseCardDeskActivity) mActivity).hideSearchTitle();
                }
                isShow = !isShow;
            }

            @Override
            public void onUpPull() {

            }
        });
    }
    /**
     * 取消按钮的点击事件
     */
    @Override
    public void cancelClick() {
        if (peekFragment() instanceof GoodsAttributesSelectParentFragment){
            ((BaseCardDeskActivity) mActivity).showSearchTitle();
            ((BaseCardDeskActivity) mActivity).hideSearchInput();
            refreshPage(mSelectList);
            viewPager.setVisibility(View.VISIBLE);
            mSearchPager.setVisibility(View.GONE);
            if (null != mSearchFragmentList) {
                mSearchFragmentList.clear();

            }
            mSearchIndicator.setVisibility(View.GONE);
            pageIndicator.setVisibility(View.VISIBLE);
        }
    }


    /**
     * 实时搜索(输入内容进行搜索操作)
     * @param text  内容
     */
    @Override
    public void searchNoRealTimeClick(String text) {
        if (peekFragment() instanceof GoodsAttributesSelectParentFragment){
                searchName = text;
            searchAttribute(searchName);
        }
    }

    //搜索
    private void searchAttribute(String searchName) {
        Map<String, Object>  map = new HashMap();
        Map<String, Number> query = new HashMap<>();
        map.put("attributeName",searchName);
        query.put("page",1);
        query.put("size",24);
        map.put("query",query);
        httpPost(ResourceConstant.SELECT_ATTRIBUTE_BYNAME,map,SEARCH_ATTRIBUTE_BYNAME,false,"");

    }

    //获取选择的属性集合
    private List<GoodsAttributesBean.ListBean> getSelectTag() {
        List<GoodsAttributesBean.ListBean> selectDatas = new ArrayList<>();
        for (int i = 0; i < fragmentList.size(); i++) {
            if (fragmentList.get(i)!=null) {
                GoodsAttributesSelectFragment currentFragment = (GoodsAttributesSelectFragment) fragmentList.get(i);
                if (currentFragment.mAdapter!=null) {
                    List<GoodsAttributesBean.ListBean> selectData = currentFragment.mAdapter.getSelectData();
                    selectDatas.addAll(selectData);
                }
            }
        }
        return selectDatas;
    }
    //获取选择的任务数量
    private int getSelectTagCount() {
        List<GoodsAttributesBean.ListBean> selectDatas = new ArrayList<>();
        for (int i = 0; i < fragmentList.size(); i++) {
            if ( fragmentList.get(i)!=null){
                GoodsAttributesSelectFragment currentFragment = (GoodsAttributesSelectFragment) fragmentList.get(i);
                if (currentFragment.mAdapter!=null){
                    List<GoodsAttributesBean.ListBean> selectData = currentFragment.mAdapter.getSelectData();
                    selectDatas.addAll(selectData);
                }
            }
        }
        return selectDatas.size();
    }
    @Override
    public void requestDatas() {
        mSelected.setOnClickListener(this);
        mConfirm.setOnClickListener(this);
    }
    public void onEventMainThread(RulesEvent event) {
        switch (event.getMsg()){
            case "notify":
                GoodsAttributesBean.ListBean   bean = (GoodsAttributesBean.ListBean) event.getData();
                if (null!=bean){
                    LogUtils.showInfoLog("notify:"+bean.toString());
                    //可能同一个，一个是true，一个是false
                    if (!mSelectList.contains(bean)){
                        if (mSelectList.size()>0){
                            for (int i = 0; i < mSelectList.size(); i++) {
                                if (mSelectList.get(i).getAttributeUkid()==bean.getAttributeUkid()&&!bean.isSelect()){
                                    mSelectList.remove(i);
                                    break;
                                }
                                if (mSelectList.get(i).getAttributeUkid()!=bean.getAttributeUkid()&&bean.isSelect()){
                                    mSelectList.add(bean);
                                    break;
                                }
                            }
                        }else {
                            mSelectList.add(bean);
                        }
                    }else {
                        if (!bean.isSelect()){
                            mSelectList.remove(bean);
                        }
                    }
                }
                //                int selectTagCount = getSelectTagCount();
                LogUtils.showInfoLog("selectTagCount:"+mSelectList.toString());
                int selectTagCount = mSelectList.size();
                LogUtils.showInfoLog("selectTagCount:"+selectTagCount);
                if (selectTagCount>0){
                    mConfirm.setEnabled(true);
                    mSelected.setEnabled(true);
                    mSelected.setText("已选"+selectTagCount);
                }else {
                    mConfirm.setEnabled(false);
                    mSelected.setEnabled(false);
                    mSelected.setText("已选");
                }
                break;
            case "notify-Have-Chosen" :
                refreshPage(mSelectList);
                break;
        }

    }
    //刷新所有的页面
    public  void refreshPage(List<GoodsAttributesBean.ListBean>  list){
        if (null!=fragmentList){
            for (int i = 0; i < fragmentList.size(); i++) {
                if (fragmentList.get(i) != null) {
                    GoodsAttributesSelectFragment currentFragment = (GoodsAttributesSelectFragment) fragmentList.get(i);
                    if (currentFragment.mAdapter != null) {
                        currentFragment.mAdapter.refreshPage(list);
                    }
                }
            }
        }
    }
    @Override
    protected void loadDatas() {
        try {
            Bundle arguments = getArguments();
            if (null!=arguments){
                listBeen = arguments.getParcelableArrayList("AttributeList");
            }
            if (null!=listBeen){
                mSelectList.addAll(listBeen);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
      selectAttributeByName();
    }
    //根据类目找属性
    private void selectAttributeByCategory() {
        Map<String, Object> map = new HashMap();
        Map<String, Object> query = new HashMap<>();
        map.put("businessId",sp.getValue("businessId"));
        query.put("page",1);
        query.put("size",24);
        query.put("sort","create_time asc");
        map.put("query",query);
        httpPost(ResourceConstant.SELECT_ATTRIBUTE_BYCATEGORY,map,SELECT_ATTRIBUTE_BYNAME,false,"");
    }

    //根据属性名模糊查找属性
    private void selectAttributeByName() {
        Map<String, Object> map = new HashMap();
        Map<String, Object> query = new HashMap<>();
        map.put("attributeName","");
        query.put("page",1);
        query.put("size",24);
        query.put("sort","create_time asc");
        map.put("query",query);
        httpPost(ResourceConstant.SELECT_ATTRIBUTE_BYNAME,map,SELECT_ATTRIBUTE_BYNAME,false,"");
    }

    @Override
    public void onSuccess(CommonClass commonClass, int what) {
        switch (what){
            case SELECT_ATTRIBUTE_BYNAME:
                if (TextUtils.equals("0", commonClass.getCode())){
                    GoodsAttributesBean goodsAttributesBean = JSON.parseObject(commonClass.getData().toString(), GoodsAttributesBean.class);
                    int total = goodsAttributesBean.getTotal();
                    fragmentList = new ArrayList<>();
                    int count = 1;
                    if (total > mNum) {
                        if ((total - mNum) % mNum == 0) {
                            count = (total - mNum) / mNum+1;
                        } else {
                            count = (total - mNum) / mNum + 2; // 总共显示多少张卡片
                        }
                    } else {
                        count = 1;
                    }
                    for (int i = 1; i <= count; i++) {
                        GoodsAttributesSelectFragment categoryFragment = new GoodsAttributesSelectFragment();
                        Bundle bundle = new Bundle();
                        bundle.putParcelableArrayList("selectedAttribute", (ArrayList<? extends Parcelable>) mSelectList);
                        bundle.putInt("pos", i);
                        bundle.putInt("num", count);
                        categoryFragment.setArguments(bundle);
                        fragmentList.add(categoryFragment);

                    }
                    if (isAdded()){
                        adapter = new MyFragmentPagerAdapter(getChildFragmentManager(), fragmentList);
                        viewPager.setAdapter(adapter);
                        pageIndicator.setViewPager(viewPager, 0);
                    }
                }
                break;
            case SEARCH_ATTRIBUTE_BYNAME:
                if (TextUtils.equals("0", commonClass.getCode())) {
                    GoodsAttributesBean goodsAttributesBean = JSON.parseObject(commonClass.getData().toString(), GoodsAttributesBean.class);
                    int total = goodsAttributesBean.getTotal();
                    viewPager.setVisibility(View.GONE);
                    pageIndicator.setVisibility(View.GONE);
                    if (total<=0){
                        mLoadingView.setVisibility(View.VISIBLE);
                        mLoadingView.showEmptyView(true);
                        mLoadingView.setEmptyListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                mLoadingView.showProgressView(true);
                                searchAttribute(searchName);
                            }
                        });
                        return;
                    }
                    mSearchIndicator.setVisibility(View.VISIBLE);
                    mSearchPager.setVisibility(View.VISIBLE);
                    mSearchFragmentList = new ArrayList<>();
                    int count = 1;
                    if (total > mNum) {
                        if ((total - mNum) % mNum == 0) {
                            count = (total - mNum) / mNum+1;
                        } else {
                            count = (total - mNum) / mNum + 2; // 总共显示多少张卡片
                        }
                    } else {
                        count = 1;
                    }

                    for (int i = 1; i <= count; i++) {
                        GoodsAttributesSelectFragment categoryFragment = new GoodsAttributesSelectFragment();
                        Bundle bundle = new Bundle();
                        bundle.putParcelableArrayList("selectedAttribute", (ArrayList<? extends Parcelable>) mSelectList);
                        bundle.putString("attributeName",searchName);
                        bundle.putInt("pos", i);
                        bundle.putInt("num", count);
                        categoryFragment.setArguments(bundle);
                        mSearchFragmentList.add(categoryFragment);

                    }
                    if (isAdded()) {
                        mSearchAdapter = new MyPagerAdapter(getChildFragmentManager(), mSearchFragmentList);
                        mSearchPager.setAdapter(mSearchAdapter);
//                    viewPager.setOffscreenPageLimit(fragmentList.size());
                        mSearchIndicator.setViewPager(mSearchPager, 0);
//                    pageIndicator.setOnPageChangeListener(mlistener);
                    }
                }
                break;

        }

    }

    @Override
    public void onReLoad(int code) {
        loadDatas();
    }

    @Override
    public void onClick(View v) {
        isShow = true ;
        ((BaseCardDeskActivity) mActivity).hideSearchInput();
        ((BaseCardDeskActivity)mActivity).hideSearchTitle();
        int i = v.getId();
        if (i == R.id.confirm) {//确认
            EventBus.getDefault().post(new GoodsEvent(GoodsEvent.GOODS_LABE,mSelectList));
            popFragment();

        } else if (i == R.id.selected) {
            GoodsAttributesHaveChosenSelectParentFragment selectParentFragment = new GoodsAttributesHaveChosenSelectParentFragment();
            Bundle bundlee = new Bundle();
            bundlee.putParcelableArrayList("mSelectList", (ArrayList<? extends Parcelable>) mSelectList);
            selectParentFragment.setArguments(bundlee);
            pushFragment(selectParentFragment);

        }
    }
}
